package com.bookhouse.controller;

import com.bookhouse.entity.Reader;
import com.bookhouse.entity.ReaderType;
import com.bookhouse.service.ReaderService;
import com.bookhouse.service.ReaderTypeService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by CiusCheung on 16/4/4.
 */
@Controller
@RequestMapping("/reader")
public class ReaderController {

    @Resource(name = "readerService")
    private ReaderService readerService;
    @Resource(name = "readerTypeService")
    private ReaderTypeService readerTypeService;

    @RequestMapping(value = "login")
    public String checkLogin(Reader user, HttpServletRequest request) {
        String hql = "From Reader u Where u.name ='" + user.getName() + "' and u.password = '" + user.getPassword() + "'";
        List<Reader> users = readerService.find(hql);
        user = users.get(0);
//        System.out.print(users);
        if (user == null) {
            request.setAttribute("errors", "此账号不存在!");
            return "login";
        }
//            else if(users.get(0).getType() == ApplicationConstants.USER_TYPE_MANAGER){
//                return "test";
//            }
        else {
            return "layout";
        }
    }

    @RequestMapping(value = "toAddReader")
    public String toAddReader(HttpServletRequest request) {
        request.setAttribute("readerTypeList", readerTypeService.findAllList(ReaderType.class));
        return "reader";
    }

    @RequestMapping(value = "addReader")
    public String addReader(Reader reader) {
        if (reader.getId() != null && reader.getId() > 0)
            readerService.update(reader);
        else
            readerService.save(reader);
        return "redirect:getAllReader";
    }


    @RequestMapping(value = "getAllReader")
    public String getAllReader(HttpServletRequest request) {
        request.setAttribute("readerList", readerService.findAllList(Reader.class));
        return "readerEditList";
    }

    @RequestMapping(value = "getReader")
    public String getReader(String readerId, HttpServletRequest request) {
        request.setAttribute("readerTypeList", readerTypeService.findAllList(ReaderType.class));
        request.setAttribute("reader", readerService.get(Reader.class, Integer.parseInt(readerId)));
        return "reader";
    }

    @RequestMapping(value = "getReaderBorrow")
    public String getReaderBorrow(String readerId, HttpServletRequest request) {
        request.setAttribute("reader", readerService.get(Reader.class, Integer.parseInt(readerId)));
        return "borrow";
    }

    @RequestMapping(value = "deleteReader")
    public String deleteReader(String readerId, HttpServletRequest request) {
        readerService.delete(Reader.class, Integer.parseInt(readerId));
        return "redirect:getAllReader";
    }

}
